<?php

namespace SunAdmin\Service\FileSystem;

use think\facade\Config;
use think\facade\Db;
use think\facade\Cache;
use yzh52521\filesystem\facade\Filesystem;

abstract class FilesystemBase
{
    protected string $currentDisk;
    protected $filesystem;
    
    public function __construct(?string $diskName = null)
    {
        $this->initFilesystem($diskName);
    }
    
    /**
     * 初始化文件系统
     */
    protected function initFilesystem(?string $diskName = null): void
    {
        // 获取配置
        $config = $this->getDiskConfig($diskName);
        $this->currentDisk = $config['disk_name'];
        
        // 动态注册
        $this->registerDisk($config);
        
        // 获取实例
        $this->filesystem = Filesystem::disk($this->currentDisk);
    }
    
    /**
     * 获取磁盘配置
     */
    protected function getDiskConfig(?string $diskName = null): array
    {
        $cacheKey = $diskName ? "filesystem_config_{$diskName}" : "filesystem_config_active";
        
        return Cache::remember($cacheKey, function() use ($diskName) {
            if ($diskName) {
                // 获取指定磁盘配置
                $result = Db::name('sunadmin_filesystem_config')
                    ->where('disk_name', $diskName)
                    ->where('status', 1)
                    ->find();
                    
                if (!$result) {
                    throw new \Exception("磁盘 [{$diskName}] 未找到或未启用");
                }
            } else {
                // 获取当前启用的磁盘配置（status=1的配置）
                $result = Db::name('sunadmin_filesystem_config')
                    ->where('status', 1)
                    ->find();
                    
                if (!$result) {
                    throw new \Exception("未找到启用的磁盘配置");
                }
            }
            
            return [
                'disk_name' => $result['disk_name'],
                'config_data' => json_decode($result['config_data'], true)
            ];
        }, 300);
    }
    
    /**
     * 动态注册磁盘
     */
    protected function registerDisk(array $config): void
    {
        $diskName = $config['disk_name'];
        $diskConfig = $config['config_data'];
        // 注入配置
        $originConfig = config("filesystem");
        $originConfig['disks'][$diskName] = $diskConfig;
        Config::set($originConfig,'filesystem');
    }

    /**
     * 清除配置缓存
     */
    public static function clearCache(?string $diskName = null): void
    {
        if ($diskName) {
            Cache::delete("filesystem_config_{$diskName}");
            Filesystem::forgetDriver($diskName);
        } else {
            Cache::delete("filesystem_config_active");
            $disks = Db::name('sunadmin_filesystem_config')->column('disk_name');
            foreach ($disks as $disk) {
                Cache::delete("filesystem_config_{$disk}");
                Filesystem::forgetDriver($disk);
            }
        }
    }
    
    /**
     * 获取当前磁盘
     */
    public function getCurrentDisk(): string
    {
        return $this->currentDisk;
    }
    
    /**
     * 获取文件系统实例
     */
    public function getFilesystem()
    {
        return $this->filesystem;
    }
} 